//
//  StudyViewController.m
//  TeacherNet
//
//  Created by slz on 2017/11/6.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "StudyViewController.h"
#import "StudyUserCourseTableViewCell.h"
#import "StudyFourViewController.h"
#import "StudyUserCourseTableViewCell.h"
#import "CouseSignUpViewController.h"
#import "MFWSDKNotificationConsts.h"

@protocol StudyTableHeaderViewDelagete<NSObject>
- (void)buttonViewClickWithIndex:(NSInteger)index;
@end

@interface StudyViewCircleButtonView : UIView
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UILabel *titleLabel;
@end

@implementation StudyViewCircleButtonView
-(instancetype)initWithTitle:(NSString *)title andImageName:(NSString *)imageName
{
    self = [super init];
    if (self){
        self.size = CGSizeMake(40, 62);
        _imageView = [UIImageView new];
        _imageView.image = [UIImage imageNamed:imageName];
        [self addSubview:_imageView];
        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.mas_equalTo(self);
            make.height.mas_equalTo(40);
        }];
        
        _titleLabel = [UILabel new];
        _titleLabel.text = title;
        _titleLabel.textColor = kDark_TextColor_Default;
        _titleLabel.fontSize = kFont_Size_Small_Title;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.and.right.mas_equalTo(self);
        }];
    }
    return self;
}
@end

@interface StudyTableHeaderView : UIView
@property (nonatomic,strong) UIImageView *avrater;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *studyDayLabel;
@property (nonatomic,strong) UILabel *allCourseLabel;
@property (nonatomic,strong) UILabel *courseTimeLabel;
@property (nonatomic,weak)id <StudyTableHeaderViewDelagete>delegate;
@end

@implementation StudyTableHeaderView


-(instancetype)init
{
    self = [super init];
    if (self){
        self.height = 285;
        self.backgroundColor = [UIColor blackColor];
        
        NSString * averater = [MFWSdkEnvironment sharedInstance].userInfo.logoUrl;
        NSString * userName = [MFWSdkEnvironment sharedInstance].userInfo.nickName;
        NSString * welcomName = [NSString stringWithFormat:@"%@ 同学,欢迎回来!",userName];
        
        _avrater = [UIImageView new];
        _avrater.layer.cornerRadius = 33;
        _avrater.layer.masksToBounds = YES;
        [_avrater sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(averater)] randomPlaceHolder:YES];
        [self addSubview:_avrater];
        [_avrater mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(66, 66));
            make.top.mas_equalTo(self.mas_top).offset(20);
            make.centerX.mas_equalTo(self.mas_centerX);
        }];
        
        UIColor * textColor = [UIColor whiteColor];
        NSInteger fontSize = kFont_Size_Cotent_Nomal;
        CGFloat labelWidth = kScreenWidth/3;
        
        _nameLabel = [UILabel new];
        _nameLabel.text = welcomName;
        _nameLabel.textColor = textColor;
        _nameLabel.fontSize = kFont_Size_Small_Title;
        _nameLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_nameLabel];
        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_avrater.mas_centerX);
            make.top.mas_equalTo(_avrater.mas_bottom).offset(10);
        }];
        
        
        UILabel * bbbLabel = [UILabel new];
        bbbLabel.text = @"总计课程";
        bbbLabel.textColor = textColor;
        bbbLabel.fontSize = fontSize;
        bbbLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:bbbLabel];
        [bbbLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.mas_centerX);
            make.top.mas_equalTo(_nameLabel.mas_bottom).offset(15);
        }];
        
        UILabel * aaaLabel = [UILabel new];
        aaaLabel.text = @"坚持学习";
        aaaLabel.textColor = textColor;
        aaaLabel.fontSize = fontSize;
        aaaLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:aaaLabel];
        [aaaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.mas_centerX).offset(-labelWidth);
            make.top.mas_equalTo(bbbLabel.mas_top);
        }];
        
        UILabel * cccLabel = [UILabel new];
        cccLabel.text = @"课程时长";
        cccLabel.textColor = textColor;
        cccLabel.fontSize = fontSize;
        cccLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:cccLabel];
        [cccLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.mas_centerX).offset(labelWidth);
            make.top.mas_equalTo(bbbLabel.mas_top);
        }];
        
        NSInteger labelMargn = 8;
        
        _studyDayLabel = [UILabel new];
        _studyDayLabel.textColor =textColor;
        _studyDayLabel.fontSize = fontSize;
        _studyDayLabel.text = @"0天";
        _studyDayLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_studyDayLabel];
        [_studyDayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(aaaLabel.mas_centerX);
            make.top.mas_equalTo(aaaLabel.mas_bottom).offset(labelMargn);
        }];
        
        _allCourseLabel = [UILabel new];
        _allCourseLabel.textColor =textColor;
        _allCourseLabel.fontSize = fontSize;
        _allCourseLabel.text = @"0个";
        _allCourseLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_allCourseLabel];
        [_allCourseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(bbbLabel.mas_centerX);
            make.top.mas_equalTo(bbbLabel.mas_bottom).offset(labelMargn);
        }];
        
        _courseTimeLabel = [UILabel new];
        _courseTimeLabel.textColor =textColor;
        _courseTimeLabel.fontSize = fontSize;
        _courseTimeLabel.text = @"0小时";
        _courseTimeLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_courseTimeLabel];
        [_courseTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(cccLabel.mas_centerX);
            make.top.mas_equalTo(cccLabel.mas_bottom).offset(labelMargn);
        }];
        
        UIView * bottomView = [UIView new];
        bottomView.backgroundColor = [UIColor whiteColor];
        [self addSubview:bottomView];
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.and.bottom.mas_equalTo(self);
            make.height.mas_equalTo(100);
        }];
        
        UIView * lineView = [UIView quickLineColorView];
        [self addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.and.bottom.mas_equalTo(self);
            make.height.mas_equalTo(.5);
        }];
        
        CGFloat itemWidth = kScreenWidth * .25;
        NSArray * titles = @[@"问答",@"作业",@"考试",@"笔记"];
        NSArray * images = @[@"study_header_icon_1",@"study_header_icon_2",@"study_header_icon_3",@"study_header_icon_4"];
        
        
        @weakify(self);
        for (int i = 0; i < titles.count; i ++ ){
            StudyViewCircleButtonView * view = [[StudyViewCircleButtonView alloc]initWithTitle:titles[i] andImageName:images[i]];
            [bottomView addSubview:view];
            view.centerX = i * itemWidth + itemWidth * .5;
            view.centerY = 50;
            
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = i;
            button.frame = view.frame;
            [button addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
                UIButton * button = sender;
                if([weak_self.delegate respondsToSelector:@selector(buttonViewClickWithIndex:)]){
                    [weak_self.delegate buttonViewClickWithIndex:button.tag];
                }
            }];
            [bottomView addSubview:button];
        }
    }
    return self;
}

- (void)updteWithModel:(StudyPageModel *)model
{
    NSString * averater = [MFWSdkEnvironment sharedInstance].userInfo.logoUrl;
    NSString * userName = [MFWSdkEnvironment sharedInstance].userInfo.nickName;
    NSString * welcomName = [NSString stringWithFormat:@"%@ 同学,欢迎回来!",userName];
    _nameLabel.text = welcomName;
    [_avrater sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(averater)] randomPlaceHolder:YES];
    _studyDayLabel.text = [NSString stringWithFormat:@"%@天",model.continueDay];
    _allCourseLabel.text = [NSString stringWithFormat:@"%@个",model.courseCount];
    _courseTimeLabel.text = [NSString stringWithFormat:@"%@时%@分",model.courseHour,model.courseMinute];
}
@end

@interface StudyViewController ()<StudyTableHeaderViewDelagete,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) YWTableView *tableView;
@property (nonatomic,strong) StudyTableHeaderView *headerView;
@property (nonatomic,strong) StudyPageModel *pageModel;
@end

@implementation StudyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showNavigationBar = NO;
    [self initViews];
    [self requestData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLogin) name:kSDK_Notify_UserDidLogin object:nil];
    // Do any additional setup after loading the view.
}

- (void)userDidLogin
{
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    
    // 马上进入刷新状态
    if (_pageModel == nil){
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)requestData
{
    
    [BaseHttpTool get:kAPI_STUDY_PAGE  params:@{@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid} success:^(id responseObj) {
        [self.tableView.mj_header endRefreshing];
        NSDictionary * dict = [[MFWJson jsonWithObject:responseObj] toDic];
        _pageModel = [StudyPageModel yy_modelWithDictionary:dict];
        [self updatePage];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.view showTip:error.localizedDescription];
    }];
}

- (void)initViews
{
    UIView * shadowView = [UIView new];
    shadowView.backgroundColor = [UIColor colorWithARGB:0xF7F8F9];
    [self.view addSubview:shadowView];
    [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.and.top.mas_equalTo(self.view);
        make.height.mas_equalTo(kStatusBarHeight);
    }];
    
    _tableView = [[YWTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    @weakify(self);
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self requestData];
    }];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.and.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(shadowView.mas_bottom);
    }];
    
    _headerView = [StudyTableHeaderView new];
    _headerView.delegate = self;
    [_tableView setTableHeaderView:_headerView];
}

- (void)updatePage
{
    [_headerView updteWithModel:self.pageModel];
    [_tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StudyCourseModel * model = _pageModel.courseList[indexPath.row];
    static NSString * resuerIndentifier = @"StudyUserCourseTableViewCell";
    StudyUserCourseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:resuerIndentifier];
    if (!cell){
        cell = [[StudyUserCourseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resuerIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell setWithModel:model];
    return cell;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _pageModel.courseList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    StudyCourseModel * model = _pageModel.courseList[indexPath.row];
    CouseSignUpViewController * signUpController = [[CouseSignUpViewController alloc]init];
    signUpController.couseId = model.courseId;
    signUpController.courseTitle = model.courseName;
    signUpController.classId = model.classId;
    [self.navigationController pushViewController:signUpController animated:YES];
}


#pragma mark - StudyTableHeaderViewDelagete

-(void)buttonViewClickWithIndex:(NSInteger)index
{
    StudyFourViewController * fourController = [[StudyFourViewController alloc]init];
    fourController.pageType = index;
    [self.navigationController pushViewController:fourController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
